﻿using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace DBSchemaService.Utils
{
    public static class TFSHelper
    {

        #region TFS Methods

        public static Identity GetTFSUser(TeamFoundationServer tfs, WorkItem workItem)
        {
            string workItemUser = string.Empty;

            if (!string.IsNullOrEmpty(workItem.Fields["Assigned To"].Value.ToString()))
            {
                workItemUser = workItem.Fields["Assigned To"].Value.ToString();
            }
            else
            {
                workItemUser = workItem.CreatedBy;
            }
            // get the Group Security Service
            IGroupSecurityService gsService = (IGroupSecurityService)tfs.GetService(typeof(IGroupSecurityService));
            // retrieve all application groups (by default: Contributors, Project Administrators, Build Services and Readers)
            // for the project this Work Item belongs to. Application groups do not contain member information.
            Identity[] applicationGroups = gsService.ListApplicationGroups(workItem.Project.Uri.AbsoluteUri);
            // for each application group
            foreach (Identity applicationGroup in applicationGroups)
            {
                // unless this is the Readers group (By default Readers do not have permissions to add/edit Work Items)
                if (applicationGroup.DisplayName != "Readers")
                {
                    // retrieve the application group again (this time with members information)
                    Identity[] groupContainer = gsService.ReadIdentities(SearchFactor.Sid, new string[] { applicationGroup.Sid }, QueryMembership.Expanded);
                    // for each group (container contains only one group)
                    foreach (Identity group in groupContainer)
                    {
                        // if this group has any members
                        if (group.Members != null)
                        {
                            foreach (string projectMemberSid in group.Members)
                            {
                                Identity validUser = gsService.ReadIdentity(SearchFactor.Sid, projectMemberSid, QueryMembership.None);
                                if (validUser.DisplayName.ToLowerInvariant() == workItemUser.ToLowerInvariant())
                                {
                                    return validUser;
                                }
                            }
                        }
                    }
                }
            }
            return null;
        }

        #endregion

    }
}